import { UserInfoDTO } from './../../../shared/service-proxy/service-proxies';
import { DictionaryDTO, CollarRecordDTO } from '@shared/service-proxy/service-proxies';
import { Component, OnInit, Injector } from '@angular/core';
import { finalize } from 'rxjs/operators';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators
} from '@angular/forms';
import { ServiceProxy, SiteDTO } from '@shared/service-proxy/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import { NzTableHelper } from '@shared/helpers/NzTableHelper';
import { MomentHelper } from '@shared/helpers/MomentHelper';
import * as moment from 'moment';
import { NullInjector } from '@angular/core/src/di/injector';


@Component({
  selector: 'app-handheld-machine',
  templateUrl: './handheld-machine.component.html',
  styleUrls: ['./handheld-machine.component.less']
})
export class HandheldMachineComponent extends AppComponentBase implements OnInit {

  tableHelper: NzTableHelper;

  keyword: string;
  userList: UserInfoDTO[] = [];
  currentUser: any;

  isVisible = false;
  validateForm: FormGroup;
  isOkLoading = false;

  isVisibleBack = false;
  validateFormBack: FormGroup;
  isOkLoadingBack = false;
  statistics: any;
  model: CollarRecordDTO = new CollarRecordDTO();

  isVisibleList: boolean = false;
  table2Helper: NzTableHelper;
  name: string;
  deviceId: string;
  dateRange = [];
  startTime: null;
  endTime: null;


  constructor(
    injector: Injector,
    private fb: FormBuilder,
    private _service: ServiceProxy) {
    super(injector);
    this.tableHelper = new NzTableHelper();
    this.table2Helper = new NzTableHelper();
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      receiverId: [null, [Validators.required]],
      receiveDate: [null, [Validators.required]],
    });

    this.validateFormBack = this.fb.group({
      backDate: [null, [Validators.required]],
    });

    this.currentUser = this.appSession.user;
    this.statistics = { stock: "", totalCount: "", siteName: "", backed: "" };
    this.load();
    this.getUserList();
  }

  load(pageIndex?: number) {
    if (typeof pageIndex !== 'undefined') {
      this.tableHelper.pageIndex = pageIndex || 1;
    }
    this.getList();
    this.getStatistics();
  }

  sort(sort: { key: string, value: string }): void {
    this.tableHelper.setSorting = sort;
    this.load();
  }

  getList() {
    this._service.getPagePDAsUsingGET(this.tableHelper.pageIndex, this.tableHelper.pageSize, undefined, this.keyword
    ).pipe(finalize(() => {
      this.tableHelper.loading = false;
    })).subscribe((result) => {
      this.tableHelper.items = result.result.fieldList;
      this.tableHelper.totalCount = result.result.totalRow;
    });
  }
  getStatistics() {
    this._service.getPdaStatisticsUsingGET().subscribe(result => {
      this.statistics = result.result;
    })
  }
  getUserList() {
    this._service.getAllUserInfosUsingGET().subscribe(result => {
      this.userList = result.result.fieldList.filter(m => m.siteId == this.currentUser.siteId);
    });
  }

  reset() {
    this.keyword = undefined;
    this.load();
  }

  // 领用状态
  showModal(id: string): void {
    this.model = new CollarRecordDTO();
    this.model.deviceId = id;
    this.model.deviceType = 1;
    this.model.state = '1';
    this.isVisible = true;
  }


  submitForm(): void {
    this.isOkLoading = true;
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    if (this.validateForm.valid) { // 验证通过
      if (this.model.id) {
        this._service.updateCollarRecordUsingPUT(this.model, this.model.id).subscribe(result => {
          this.isOkLoading = false;
          if (result.success) {
            this.message.success(this.l('save_success'));
            this.load();
            this.getStatistics();
            this.isVisible = false;
          } else {
            this.message.info(this.l(result.error.message));
          }


        }, error => {
          this.isOkLoading = false;
          this.message.error(error.message);
        });
      } else {

        this._service.createCollarRecordUsingPOST(this.model).subscribe(result => {
          this.isOkLoading = false;
          if (result.success) {
            this.message.success(this.l('save_success'));
            this.load();
            this.getStatistics();
            this.isVisible = false;
          } else {
            this.message.info(this.l(result.error.message));
          }
        }, error => {
          this.isOkLoading = false;
          this.message.error(error.message);
        });
      }
      this.load();
    } else { // 验证未通过
      this.isOkLoading = false;
      this.message.error(this.l('verify_failed_please_check_the_form_item'));
    }
  }

  handleOk(): void {
    this.submitForm();
  }

  handleCancel(): void {
    this.isVisible = false;
  }



  // 修改归还状态
  showReceiveModal(id: string): void {
    this._service.getLastCollarRecordByDeviceIdUsingGET(id).subscribe(result => {
      this.model = result.result;
    });
    this.isVisibleBack = true;
  }

  handleCancelBack(): void {
    this.isVisibleBack = false;
  }

  handleOkBack(): void {
    this.submitFormBack();
  }

  submitFormBack(): void {
    this.isOkLoadingBack = true;
    for (const i in this.validateFormBack.controls) {
      this.validateFormBack.controls[i].markAsDirty();
      this.validateFormBack.controls[i].updateValueAndValidity();
    }

    if (this.validateFormBack.valid) { // 验证通过
      if (this.model.id) {
        this._service.updateCollarRecordUsingPUT(this.model, this.model.id).subscribe(result => {
          this.isOkLoadingBack = false;
          if (result.success) {
            this.message.success(this.l('save_success'));
            this.load();
            this.getStatistics();
            this.isVisibleBack = false;
          } else {
            this.message.info(this.l(result.error.message));
          }
        }, error => {
          this.isOkLoadingBack = false;
          this.message.error(error.message);
        });
      }
      this.load();
    } else { // 验证未通过
      this.isOkLoadingBack = false;
      this.message.error(this.l('verify_failed_please_check_the_form_item'));
    }
  }

  // 获取领用记录


  handleCancelList(): void {
    this.isVisibleList = false;
  }

  loadList(id: string, pageIndex?: number) {
    if (typeof pageIndex !== 'undefined') {
      this.table2Helper.pageIndex = pageIndex || 1;
    }
    this.getCollarList(id);
  }

  sortList(id: string, sort: { key: string, value: string }): void {
    this.table2Helper.setSorting = sort;
    this.loadList(id);
  }


  resetList(deviceId: string) {
    this.name = undefined;
    this.startTime = null;
    this.endTime = null;
    this.loadList(deviceId);
  }

  onChange(result: any): void {
    if (result) {
      this.startTime = result[0];
      this.endTime = result[1];
    }
    console.log('onChange: ', result);
  }

  getCollarList(id: string) {
    this._service.getCollarRecordsWithPageUsingGET(id, this.name, this.table2Helper.pageIndex, this.table2Helper.pageSize, this.startTime, this.endTime
    ).pipe(finalize(() => {
      this.table2Helper.loading = false;
    })).subscribe((result) => {
      this.table2Helper.items = result.result.fieldList;
      this.table2Helper.totalCount = result.result.totalRow;
    });
  }

  showListModal(deviceId: string) {
    this.isVisibleList = true;
    this.deviceId = deviceId;
    this.loadList(deviceId);
  }
}
